//
//  DesignViewController.m
//  Surveyer
//
//  Created by Qikun Guo on 13-8-12.
//  Copyright (c) 2013年 Tim. All rights reserved.
//
#import "DesignViewController.h"
#import "DesignViewCell.h"
#import "DesignItemPickerViewController.h"
#import "TKLabelTextFieldCell.h"

@interface DesignViewController ()

@end

@implementation DesignViewController
@synthesize currentSurvey, tableview;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self.tableview selector:@selector(reloadData) name:SurveyerStoreUpdateNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
    self.navigationItem.rightBarButtonItem = addButton;
    self.title = currentSurvey.title;
    UINib *nib = [UINib nibWithNibName:@"DesignViewCell" bundle:nil];
    [tableview registerNib:nib forCellReuseIdentifier:@"DesignViewCell"];
    
    optionsName = @[@"Time", @"showPageIndicator"];
    optionsKey = @[@"time", @"showPageIndicator"];
    
    if (currentSurvey.time != 0)
    {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Caution!", @"title if edit a survey with result") message:NSLocalizedString(@"The survey you are editing has been surveyed before, please be extremely cautious. Some changes may result in inablity to access the result forever", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"I Understand", nil) otherButtonTitles:nil, nil];
        [av show];
    }
    
    [tableview footerViewForSection:1].textLabel.text = [NSString stringWithFormat:@"%@ %d", NSLocalizedString(@"Number of Survey Items:", @"footer"), currentSurvey.items.count];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [tableview reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[SurveyerStore defaultStore] saveChanges];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            //title, description
            return 2;
            break;
        default:
            //surveyItems
            return currentSurvey.items.count;
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            //title, description
            return [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Basic Information of", @"section name1"), currentSurvey.title];
            break;
        default:
            //surveyItems
            return NSLocalizedString(@"Survey Questions", @"section name2");
            break;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if (section == 0)
        return nil;
    return [NSString stringWithFormat:@"%@ %d", NSLocalizedString(@"Number of Survey Items:", @"footer"), currentSurvey.items.count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            TKLabelTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TText"];
            if (!cell)
                cell = [[TKLabelTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TText"];
            cell.delegate = currentSurvey;
            switch (indexPath.row) {
                case 0:
                    cell.key = @"title";
                    cell.label.text = NSLocalizedString(@"Title", nil);
                    break;
                default:
                    cell.key = @"intro";
                    cell.label.text = NSLocalizedString(@"Description", nil);
                    break;
            }
            return cell;
            break;
        }
            
        case 1:
        {
#warning wrong way! load the nib!
            DesignViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"designCell"];
            if (!cell)
                cell = [[DesignViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"designCell"];
            SurveyItem *item = [[currentSurvey items] objectAtIndex:indexPath.row];
            cell.textLabel.text = item.title;
            [cell initByType:item.type];
            return cell;
            break;
        }
        default:
        {
            TKLabelTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TText"];
            if (!cell)
                cell = [[TKLabelTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TText"];
            cell.delegate = currentSurvey;
            cell.key = [optionsKey objectAtIndex:indexPath.row];
            cell.label.text = [optionsName objectAtIndex:indexPath.row];
            return cell;
            break;
        }
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [currentSurvey removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:indexPath.row]];
        [tableView endUpdates];
        [tableView footerViewForSection:1].textLabel.text = [NSString stringWithFormat:@"%@ %d", NSLocalizedString(@"Number of Survey Items:", @"footer"), currentSurvey.items.count];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
        return YES;
    return NO;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
        return YES;
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    SurveyItem *item = [[currentSurvey.items objectAtIndex:sourceIndexPath.row] copy];
    [currentSurvey insertObject:item inItemsAtIndex:destinationIndexPath.row];
    [currentSurvey removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:sourceIndexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        DesignItemPickerViewController *dipvc = [[DesignItemPickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
        dipvc.currentItem = [[currentSurvey items] objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:dipvc animated:YES];
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

#pragma mark - @Selectors
- (void)add
{
    SurveyItem *item = [[SurveyerStore defaultStore] createSurveyItemInSurvey:currentSurvey];
    DesignItemPickerViewController *dipvc = [[DesignItemPickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
    dipvc.currentItem = item;
    [self.navigationController pushViewController:dipvc animated:YES];
}
@end
